<template>
  <div>
    <el-dialog
      :model-value="props.dialogVisible"
      title="固件升级"
      width="500px"
      :close-on-click-modal="false"
      :before-close="handleClose">
      <el-form ref="updateFormRef" :model="updateForm" :rules="updateFormRules" label-width="120px" @submit.prevent>
        <el-form-item label="设备选择：" prop="name">
          <el-input v-model="updateForm.name" clearable placeholder="请选择设备" readonly></el-input>
        </el-form-item>
        <el-form-item label="升级固件目标：" prop="target">
          <el-select v-model="updateForm.target" clearable placeholder="请选择升级固件目标" style="width: 100%;">
            <el-option
              v-for="item in targetOptions"
              class="firmware-item"
              :key="item.id"
              :label="item.firmwareName"
              :value="item.firmwareName">
              <span class="pro">{{item.productName}}</span>
              <span class="ver">{{item.firmwareName}}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="升级时间：" prop="time">
          <el-select v-model="updateForm.time" clearable placeholder="请选择升级时间" style="width: 100%;">
            <el-option
              v-for="item in timeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item> -->
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="handleSubmit(updateFormRef)">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="FirmwareUpdateFrom">
import { ref, reactive, watch, ComponentInternalInstance, getCurrentInstance } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { firmwareUpdateCmd } from '@/api/firmware-update'
import { firmwareList } from '@/api/firmware-manage'

const { proxy } = getCurrentInstance() as ComponentInternalInstance

const emit = defineEmits(['submit', 'update:dialogVisible'])
const props = defineProps({
  dialogVisible: {
    type: Boolean,
    default: false
  },
  formData: {
    type: Object,
    default: {}
  }
})

const targetOptions = ref<any>([])
const timeOptions = ref<any>([])
const updateForm = reactive({
  name: '',
  target: '',
  // time: ''
})
const updateFormRef = ref<FormInstance>()
const updateFormRules = reactive<FormRules>({
  name: [
    { required: true, message: '请选择设备！' }
  ],
  target: [
    { required: true, message: '请选择升级固件目标！' }
  ],
  // time: [
  //   { required: true, message: '请选择升级时间！' }
  // ],
})
const selected = <any>ref([])

watch(() => props.dialogVisible, async (newVal) => {
  if (newVal) {
    getFirmwareData()
    if (props.formData.length === 1) {
      updateForm.name = props.formData[0].deviceName
    } else {
      updateForm.name = `已选择${props.formData.length}个设备`
    }
  }
})

// 重置表单
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

// 关闭弹窗
const handleClose = () => {
  selected.value = []
  updateForm.name = ''
  resetForm(updateFormRef.value)
  proxy?.$emit('update:dialogVisible', false)
}

// 获取固件下拉数据
const getFirmwareData = async () => {
  await firmwareList({}).then((res: any) => {
    if (res.code === 0) {
      targetOptions.value = [...res.list]
    } else {
      ElMessage.error(`${res.msg}`)
    }
  }).catch(err => {
    console.log(err)
  })
}

// 提交表单
const handleSubmit = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async (valid, fields) => {
    if (valid) {
      let deviceSnList = <any>[]
      props.formData.map((item: any) => {
        deviceSnList.push(item.deviceSn)
      })
      let params = {
        deviceSnList,
        version: updateForm.target
      }
      await firmwareUpdateCmd(params).then((res: any) => {
        if (res.code === 0) {
          ElMessage.success(`升级指令发送成功！`)
          emit('submit')
          handleClose()
        } else {
          ElMessage.error(`${res.msg}`)
        }
      }).catch(err => {
        console.log(err)
      })
    }
  })
}
</script>

<style lang="stylus" scoped>
.firmware-item
  // height auto
  // line-height 1
  .ver
    font-weight bold
    float right
</style>
